package minio

import (
	"fmt"
	"github.com/google/wire"
	"github.com/minio/minio-go"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

// ClientType 定义日志 client 结构体
type ClientType struct {
	Mio     *minio.Client
	Options *Options
}

// Options log option
type Options struct {
	Endpoint        string
	AccessKeyID     string
	SecretAccessKey string
	UseSSL          bool
	Bucket          string
}

// NewOptions new log option
func NewOptions(v *viper.Viper, logger *zap.Logger) (*Options, error) {
	var (
		err error
		o   = new(Options)
	)
	if err = v.UnmarshalKey("minio", o); err != nil {
		return nil, errors.Wrap(err, "unmarshal mio option error")
	}
	logger.Info("load mio options success", zap.Any("mio options", o))
	return o, err
}

// New new esClient
func New(o *Options, logger *zap.Logger) (*ClientType, error) {
	var (
		err error
		mio *minio.Client
	)
	mio, err = minio.New(o.Endpoint, o.AccessKeyID, o.SecretAccessKey, o.UseSSL)
	if err != nil {
		return nil, err
	}
	exist, err := mio.BucketExists(o.Bucket)
	if err != nil {
		return nil, err
	}
	if !exist {
		err = mio.MakeBucket(o.Bucket, "us-east-1")
		if err != nil {
			return nil, err
		}
		err = mio.SetBucketPolicy(o.Bucket, fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/*"]}]}`, o.Bucket))
		if err != nil {
			return nil, err
		}
		logger.Info("load mio init set bucket success", zap.Any("mio options", o.Bucket))
	}
	return &ClientType{
		Mio:     mio,
		Options: o,
	}, nil
}

// ProviderSet dependency injection
var ProviderSet = wire.NewSet(New, NewOptions)
